package com.manage.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.manage.platform.context.UserContext;
import com.manage.platform.dto.DictDto;
import com.manage.platform.dto.query.DictPageQuery;
import com.manage.platform.entity.DictEntity;
import com.manage.platform.exception.CommonException;
import com.manage.platform.exception.EmError;
import com.manage.platform.mapper.DictMapper;
import com.manage.platform.utils.RPage;
import com.manage.platform.vo.DictVo;
import com.manage.platform.vo.UserVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * YWD
 * 2025/9/19
 */
@Slf4j
@AllArgsConstructor
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, DictEntity> {

    private final DictValueServiceImpl dictValueService;

    public RPage<List<DictVo>> getDictPage(DictPageQuery query) {
        final Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<DictVo> list = this.baseMapper.getDictPage(query);
        return RPage.ok(list, query.getPage(), query.getLimit(), page.getTotal());
    }

    public DictVo getDictDetails(Long id) {
        return this.baseMapper.getDictDetails(id);
    }

    public Boolean saveDict(DictDto dto) {
        //是否重复
        LambdaQueryWrapper<DictEntity> queryWrapper = new LambdaQueryWrapper<DictEntity>();
        queryWrapper.eq(DictEntity::getIsDeleted, 0)
                .eq(DictEntity::getName, dto.getName())
                .or().eq(DictEntity::getType, dto.getType());
        List<DictEntity> list = list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            throw new CommonException(EmError.DICT_IS_EXIST);
        }
        UserVo userVo = UserContext.getUser();
        dto.setUserId(userVo.getId());
        return save(BeanUtil.copyProperties(dto, DictEntity.class));
    }

    public Boolean updateDict(DictDto dto) {
        //是否重复
        LambdaQueryWrapper<DictEntity> queryWrapper = new LambdaQueryWrapper<DictEntity>();
        queryWrapper.eq(DictEntity::getIsDeleted, 0)
                .eq(DictEntity::getName, dto.getName())
                .or().eq(DictEntity::getType, dto.getType())
                .ge(DictEntity::getId, dto.getId());
        List<DictEntity> list = list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            throw new CommonException(EmError.DICT_IS_EXIST);
        }
        return updateById(BeanUtil.copyProperties(dto, DictEntity.class));
    }

    public Boolean deleteDict(Long id) {
        //字典是否正在使用(TODO)
        dictValueService.removeByDictId(id);
        return removeById(id);
    }


}
